#include <string.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(int argc, char **argv)
{
    int sockfd, new_sockfd;
    struct sockaddr_in s_addr, c_addr;
    unsigned int my_port;   
    if (argv[2])
        my_port = atoi(argv[2]);
    else
        my_port = 7654;
    
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        perror("socket");
        exit(-1);
    }

    s_addr.sin_family = AF_INET;
    s_addr.sin_port = htons(my_port);
    if (argv[1])
        s_addr.sin_addr.s_addr = inet_addr(argv[1]);
    else
        s_addr.sin_addr.s_addr = INADDR_ANY;

    if(bind(sockfd, (struct sockaddr*)&s_addr, sizeof(s_addr))) {
        perror("bind");
        exit(-1);
    }
    listen(sockfd, 5);
    printf("waiting for client\n");
    int len = sizeof(c_addr);
    while (1) {
        new_sockfd = accept(sockfd, (struct sockaddr *)&c_addr, &len);
        printf("a new client coming\n");
    }
    return 0;
}
